<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-07-13 13:09:44
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Purchase;


use App\Http\Services\Service;
use App\Repositories\PurchaseApplyDetailsRepository;
use App\Repositories\PurchaseApplyRepository;

class ApplyService extends Service
    {
    public $details;
    public function __construct(PurchaseApplyRepository $repository, PurchaseApplyDetailsRepository $details)
        {
        $this->repository = $repository;
        $this->details    = $details;
        }

    public function list()
        {
        $data = $this->details->condition(request())->getGrid();
        return $data;
        }
    protected function save($request)
        {
        $data = $request->toArray();
        $data = $this->repository->autosave($data);
        if ($data->status_id == 1) {
            fail("已审核，禁止编辑");
            }
        }
    protected function audit()
        {
        return $this->getApply()->filter(function ($apply)
            {
            if ($apply->status_id == 1)
                fail("单据【{$apply->code}】已审核！");
            auditSave($apply);
            $apply->details->filter(
                function ($v)
                    {
                    $v->remain_quantity = $v->quantity;
                    auditSave($v);
                    }
            );
            });
        }

    protected function noaudit()
        {
        return $this->getApply()->filter(function ($apply)
            {
            if ($apply->status_id == 0)
                fail("单据【{$apply->code}】未审核！");

            auditSave($apply, false);
            $apply->details->filter(
                function ($v)
                    {
                    if ($v->remain_quantity != $v->quantity)
                        fail("单据【{$v->code}】已下采购订单！无法反审核");
                    auditSave($v, false);
                    }
            );
            });
        }
    public function getApply()
        {
        $ids = $this->details->whereIn("id", $this->getRequestIds())->pluck("main_id");
        return $this->repository->whereIn("id", $ids)->get();
        }
    protected function delete($request)
        {
        $ids = [];
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($detail) use (&$ids)
            {
            if ($detail->status_id == 1)
                fail("单据已审核！");
            $ids[$detail['main_id']] = $detail['main_id'];
            $detail->delete();
            });
        $newids = $this->details->whereIn("main_id", $ids)->pluck("main_id");
        return $this->repository
            ->whereIn("id", $ids)
            ->whereNotIn("id", $newids)->get()->filter(function ($apply)
                {
                $apply->delete();
                });

        // $this->details->delete($request->input("ids"));
        }
    }